//
//  NewsViewModel.swift
//  知乎日报Demo
//
//  Created by Ann on 2017/10/17.
//  Copyright © 2017年 Ann. All rights reserved.
//

import Foundation
import Alamofire
//Step.2 加载新闻数据
class NewsViewModel {
    //2.5 今天的新闻
    var todayNews:StatusList?
    
    var news = [StatusList]()
    
    //2.1 创建加载今天新闻的方法
    func refreshTodayNews(finished:@escaping (_ isSuccess:Bool)->()){
        
        //使用Alamofire框架 获取最新的新闻列表
        // 获得今天的新闻，todayNews赋值
        Alamofire.request(LATEST_NEWS_URL).responseJSON { (response) in
            
            let result = response.result.value as? [String: AnyObject]
            //  print("rescult\(result)")
            //2.2 根据数据创建 Status 新闻模型 
            guard result != nil else{
                print("result为:\(String(describing: result))")
                finished(false)
                return }
            
            
            //最热新闻
            let top_stories = result?["top_stories"] as? [[String: AnyObject]]
            
            //最新新闻
            let stories = result?["stories"] as? [[String: AnyObject]]
            let dateDict =   result!["date"]!
            
          let date = stringToInt(str: (dateDict as! String))
            //遍历最热新闻
            var topNews:[Status] = [Status]()
            
            var lastestNews: [Status] = [Status]()
            
            for topNewsDict in top_stories! {
                
                topNews.append(Status(dict: topNewsDict))
                
            }
            for lastestNewsDict in stories! {
                
                lastestNews.append(Status(dict: lastestNewsDict))
                
            }
            
            
            if let day = self.todayNews?.date{
                
                if  day == date as! Int {
                    
                    self.todayNews?.news = lastestNews
                    self.todayNews?.topNews = topNews
                    self.news.remove(at: 0)
                    self.news.insert(self.todayNews!, at: 0)
                    finished(true)
                }else{
                    //日期不一样了,就说明可能都过了一天了.那么就需要把原来的todayNews放入一般的 news中
         
                    self.news.removeAll()
                    self.todayNews?.date = date as! Int
                    self.todayNews?.news = lastestNews
                    self.todayNews?.topNews = topNews
                    self.news.insert(self.todayNews!, at: 0)
                    finished(true)
                }
                
                
            }else {
                
                self.todayNews = StatusList()
                self.todayNews?.date = Int(date)
                self.todayNews?.news = lastestNews
                self.todayNews?.topNews = topNews
                
                self.news.append(self.todayNews!)
                finished(true)
              
            }
            
            
        }
        
        
        
    }
    
    func getYesterdayNews(finished:@escaping (_ isSuccess:Bool)->()){
        
        guard news.first != nil  else {
            return
        }
        
        let getNextDayByLastDate = news.last!.date
      Alamofire.request(SOMEDAY_NEWS_URL+"\(getNextDayByLastDate)").responseJSON { (response) in
            
            guard response.error == nil else{
                finished(true)
                print(" response.error:\( response.error )")
                return
            }
            let result = response.result.value as? [String:AnyObject]
            
            //最热新闻
            let top_stories = result?["top_stories"] as? [[String: AnyObject]]
            
            //最新新闻
            let stories = result?["stories"] as? [[String: AnyObject]]
            
            let dateDict =   result!["date"]!
            
            let date =  stringToInt(str: (dateDict as! String))
            //遍历最热新闻
        
            
            var lastestNews: [Status] = [Status]()
        
            for lastestNewsDict in stories! {
                
                lastestNews.append(Status(dict: lastestNewsDict))
                
            }
            
            //拼接数组
            
            self.news.append(StatusList(date: date, news: lastestNews, topNews: nil))
              finished(true)
  
            
        }
        
      
        
        func getNextDateInt(_ date:Int) ->Int? {
            
            let formatter:DateFormatter = DateFormatter()
            formatter.dateFormat = "yyyyMMdd"
            let today=formatter.date(from: "\(date)")
            
            if let m_today = today {
                let tomorrow = Date(timeInterval: (24 * 60 * 60), since: m_today)
                return Int(formatter.string(from: tomorrow))
            }
            
            return nil
        }
        
        
    }

}
